package test.netty.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    // 生成秘钥对
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        keyPairGenerator.initialize(1024);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        return keyPair;
    }

    // 获取公钥(Base64编码)
    public static String getPublicKey(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();

        byte[] bytes = publicKey.getEncoded();

        return byte2Base64(bytes);
    }

    // 获取私钥(Base64编码)
    public static String getPrivateKey(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();

        byte[] bytes = privateKey.getEncoded();

        return byte2Base64(bytes);

    }

    // 将Base64编码后的公钥转换成PublicKey对象
    public static PublicKey string2PublicKey(String pubStr) throws Exception {
        byte[] keyBytes = base642Byte(pubStr);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        return publicKey;
    }

    // 将Base64编码后的私钥转换成PrivateKey对象
    public static PrivateKey string2PrivateKey(String priStr) throws Exception {
        byte[] keyBytes = base642Byte(priStr);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;
    }

    // 公钥加密
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] bytes = cipher.doFinal(content);

        return bytes;
    }

    // 私钥解密
    public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");

        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] bytes = cipher.doFinal(content);

        return bytes;
    }

    // 字节数组转Base64编码
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(bytes);
    }

    // Base64编码转字节数组
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();

        return decoder.decodeBuffer(base64Key);
    }

    // Base64字符串转正常字符串
    public static String base64ToStr(String str) {
        if(null != str){
            Base64.Decoder decoder = Base64.getDecoder();
            try {
                return new String(decoder.decode(str.getBytes()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        // KeyPair keyPair = getKeyPair();
        // System.out.println("public key:" + getPublicKey(keyPair));
        // System.out.println("ptivate key:" + getPrivateKey(keyPair));
        String pass = "FRAmP2rBf0ZV0R0VaDzPe6NkM0E2CFxqcdQPXJXfXePzzHxugCI7ILH3OGtFaXzKQKDEGIJG68Xi8UVP0IbzH3XkdG8dv7bzzs2Y//RaqqBWWBdbPjkHMQkTuq4qHg6mUwwzFOpGyTCOk30D50db1oEAXmdopg9qupxxc3tkVTc=";
        String pass2 = "HgSxmC5SeIlQ8kcQQxrr2kX1pQmmlvYxKaeLmlgzFqvf9DdBqn53l0FyZmVF2JSfRC1l6Y8vAttZODEZ/IZ1oyeyS69HymKaImiMI40cvD/MhK+yE4crORIbfaFNnfThq+RTSW5koZma+SQ4YW/gfxkqnAaww3kDOrDaAAAuSKc=";
        PrivateKey privateKey = string2PrivateKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI0ieenzDoq8Yv1sj8Qljn4i94xY+U2fSlVHOknpEOvccKjx+Ca2C5wBbWfxRR/0QPbqlj8iVsI6s6d+bqBy+N75xLPHbf4WnzH/xn+qj0Zmovrdd3ofhsthduH8U2DMieE10H0aaTCXMVwI5qd0j6sM3/L3l/hx3v1NeN7ZJ5e/AgMBAAECgYA380v7iCTisS5ZIzmXXAAyVzBmDju/Hv/78MHV3TSdHIX5I/vpdNADZ7l0tHxf35gFixhHLRjR5S2loATBTPMF8g7tNdlUcesnl/fLjXBNPLn6Licktrpxa4Cdirf0DRcxdi25itrvMSRjrs84G38Kx/iNF+lPMy+2/ZqdgLKCkQJBANwc3OrhPUP/6swO8FnBpwog+O9s0VB6FovFsxAl3kbku+8PHnufr3i5rdSZ3Y526o0aW8BjJBT0Z0XdwsYrzrcCQQCkJTNtF9wnS8aYRsr8OTRiGjkbe2wpo8vXxVU9LWTVXb4lw7Uljn3+p7ehypjciZb/JJOONR/BhRrH41z+rPc5AkAUX4+LJgH3s05WSOOySxxc8aRY9OeC3WoM0eW7DuY+BZnnjKyzoJorQHR4gy1grF0VZmUrr4F9dwnAC8ClexSNAkBpAjuCAQ+gPAPSiwd0kAwI7om2ISEzCkxvvxgmyRGGxi/M7QTH//5umVEKuhdMjuEAXJ/hC+9C2Con0jY93t1RAkEAvy5LPpCzDdBN3bTEeMaXHcEjrC3eWL7OMBDVTpBcdZEEMsYfeYlRHF43cJ0rEJGZgTSa0HgMEP6wRP7l+sf23w==");
        String p1 = byte2Base64(privateDecrypt(base642Byte(pass), privateKey));
        String p2 = byte2Base64(privateDecrypt(base642Byte(pass2), privateKey));
        System.out.println("pass:" + base64ToStr(p1));
        System.out.println("pass2:" + base64ToStr(p2));
    }
}